/**
 * Created by Administrator on 15-1-7.
 */
require.config({
    baseUrl:PUBLIC + "/Admin/js/lib"
});
define(function(require){
    var $ = require('jquery');
    require('jquery.form');
    window.$ = window.jQuery = $;
    var c=require('../common');
    var dialog = require('bDialog/dialog');
    window.dialog=dialog;
    require('tips/msgbox');
    require('datetimepicker/datetimepicker');
    require('select');
    require('webui');

    $(function(){
        var current_channel   = null;
        var current_menu_sub  = null;
        var viewed_channel	  = new Array();

        $('#type_sel').selectbox();
        //日期时间选择器
        $('#start_time').datetimepicker({
            format:'Y-m-d',
            onShow:function( ct ){
                var end_time = $('#end_time').val();
                this.setOptions({
                    maxDate:end_time?new Date(Date.parse(end_time.replace(/-/g,"/"))):false
                })
            },
            closeOnDateSelect:true,
            timepicker:false
        });

        $('#end_time').datetimepicker({
            format:'Y-m-d',
            onShow:function( ct ){
                var start_time = $('#start_time').val();
                this.setOptions({
                    minDate:start_time?new Date(Date.parse(start_time.replace(/-/g,"/"))):false
                })
            },
            closeOnDateSelect:true,
            timepicker:false
        });

        //切换频道（即头部的tab）
        function switchChannel(channel) {
            $('.main_nav').find('a').removeClass('on');
            $('#channel_'+current_channel).removeClass('on');
            $('#channel_'+channel).addClass('on');
            $('#root_'+current_channel).css('display', 'none');
            $('#root_'+channel).css('display', 'block');
            var tmp_menulist = $('#root_'+channel).find('a');
            tmp_menulist.each(function(i, n) {
                // 防止重复点击ROOT菜单
                if( i == 0 && $.inArray($(n).attr('id'), viewed_channel) == -1 ) {
                    $(n).click();
                    viewed_channel.push($(n).attr('id'));
                }
                if ( i == 1 ) {
                    $(n).click();
                }
            });
            current_channel = channel;
        }

        function switch_root_menu(root) {
            root = $('#tree_'+root);
            if (root.css('display') == 'block') {
                root.css('display', 'none');
                root.parent().css('backgroundImage', 'url('+PUBLIC+'/Admin/images/ArrOff.png)');
            }else {
                root.css('display', 'block');
                root.parent().css('backgroundImage', 'url('+PUBLIC+'/Admin/images/ArrOff.png)');
            }
        }

        function switch_sub_menu(sub, url) {
            if(current_menu_sub) {
                $('#menu_'+current_menu_sub).attr('class', 'submenuA');
            }
            $('#menu_'+sub).attr('class', 'submenuB');
            current_menu_sub = sub;
            parent.MainIframe.location = url;
        }

        /* 按下F5时仅刷新iframe页面 */
        function inactiveF5(e) {
            e=window.event||e;
            var key = e.keyCode;
            if (key == 116){
                parent.MainIframe.location.reload();
                if(document.all) {
                    e.keyCode = 0;
                    e.returnValue = false;
                }else {
                    e.cancelBubble = true;
                    e.preventDefault();
                }
            }
        }

        $('.switchChannel').off().on('click',function(){
           var channel_id = $(this).data('id');

            switchChannel(channel_id);
        });

        $('.switch_root_menu').off().on('click',function(){
           var id = $(this).data('id');

            switch_root_menu(id);
        });

        $('.switch_sub_menu').off().on('click',function(){
            var id = $(this).data('id');
            var url = $(this).data('url');

            switch_sub_menu(id,url);
        });

        switchChannel('key_1');//初始化频道

        document.onkeydown=inactiveF5;//按F5刷新

        //弹出信息修改页面
        $('.modifyPass').off().on('click',function(){
            var d = dialog({width:400,padding:'0 40px 0 0',title:'修改密码',url:'/Public/updateinfo',end:function(){
            },ok:function(){
                var old_password = $.trim($('#old_password').val());
                var new_password = $.trim($('#new_password').val());
                var que_password = $.trim($('#que_password').val());
                // 判断是否输入内容
                if(empty(old_password)){
                    ZENG.msgbox.show('旧密码不能为空', 5,2000);
                    $('#old_password').focus();
                    return false;
                }
                if(empty(new_password)){
                    ZENG.msgbox.show('新密码不能为空', 5,2000);
                    $('#new_password').focus();
                    return false;
                }
                if(new_password.length<5 || new_password.length>15){
                    ZENG.msgbox.show('密码长度在5~15个字符', 5,2000);
                    $('#new_password').focus();
                    return false;
                }
                if(empty(que_password)){
                    ZENG.msgbox.show('请输入确认密码', 5,2000);
                    $('#que_password').focus();
                    return false;
                }
                if(que_password!=new_password){
                    ZENG.msgbox.show('两次密码输入不一致', 5,2000);
                    $('#que_password').focus();
                    return false;
                }

                $.post(ADMINHOST+'/Public/doUpdateInfo',{que_password:que_password,old_password:old_password},function(msg){
                    if(msg.status == 1) {
                        ZENG.msgbox.show(msg.info, 4,1000);
                        setTimeout(function() {
                            window.top.location.href=ADMINHOST+'/Public/logout';
                        }, 1000);
                    } else {
                        ZENG.msgbox.show(msg.info, 5,2000);
                        return false;
                    }
                });

                return false;
            },cancel:function(){},okVal:'保存',cancelVal:'取消'});
            return false;
        });

        //点击刷新仅刷新框架
        $('.refresh').off().on('click',function(){
            parent.MainIframe.location.reload();
        });

        //注销
        $('.logout').off().on('click',function(){
            dialog({width:400,title:'温馨提示',icon:'warning',content:'确认要退出登录？',ok:function(){
                $.post(ADMINHOST+'/Public/logout','',function(data){
                    if(data.status==1){
                        ZENG.msgbox.show(data.info, 4,1000);
                        setTimeout(function(){
                            location.href = ADMINHOST+"/Public/index";
                        },1500);
                    } else {
                        ZENG.msgbox.show(data.info, 5,2000);
                    }
                },'json');
            },
            cancel:function(){},
            okVal:'确定',cancelVal:'取消'});
        });
		
		//状态修改
        $('.status').off().on('click',function(){
            var id = $(this).data('id');
			var status = $(this).data('status');
			var opt = $(this).data('opt');

            if(id=='') {
                dialog({title:'温馨提示',height:100,icon:'error',content:'请先选择要操作的对象'}).time(3);
                return false;
            }
			if(opt=='del'){
				var str = '确定要删除此记录？';
			}else{
				var str = '请确认是否要修改此记录？';
			}
            dialog({title:'温馨提示',height:100,icon:'warning',content:str,ok:function(){
                $.post(URL+'/'+opt,{'id':id,'status':status},function(data){
					if(data.status == 1) {
                        c.success(data.info,1000,location.reload());
                    } else {
                        c.error(msg.info,2000);
                    }
                },'json');
            },
            cancel:function(){},
            okVal:'确定',cancelVal:'取消'});
        });

        //禁用与启用自动任务
        $('.editStatus').off().on('click',function(){
            var id = $(this).parent().data('id');
            var status = $(this).data('status');

            dialog({title:'温馨提示',height:100,icon:'warning',content:'是否确定操作该数据？',ok:function(){
                $.post(URL+'/setStatus',{'id':id,'status':status},function(data){
                    if(data.status){
                        ZENG.msgbox.show(data.info, 4,1000);
                        setTimeout(function(){ location.reload(); },1000);
                    } else {
                        ZENG.msgbox.show(data.info, 5,2000);
                    }
                },'json');
            },
                cancel:function(){},
                okVal:'确定',cancelVal:'取消'});
        });

        //删除自动任务
        $('.delData').off().on('click',function(){
            var id = $(this).parent().data('id');

            dialog({title:'温馨提示',height:100,icon:'warning',content:'确认删除该自动任务？',ok:function(){
                $.post(URL+'/delCrontabConfig',{'id':id},function(data){
                    if(data.status){
                        ZENG.msgbox.show(data.info, 4,1000);
                        setTimeout(function(){ location.reload(); },500);
                    } else {
                        ZENG.msgbox.show(data.info, 5,2000);
                    }
                },'json');
            },
                cancel:function(){},
                okVal:'确定',cancelVal:'取消'});
        });

        //添加与编辑自动任务
        $('#detail_cron_form').ajaxForm({
            beforeSubmit:checkCronForm,
            success:completeCronForm,
            dataType:'json'
        });

        function checkCronForm(){
            var name = filterHtml($.trim($('input[name="name"]').val()));
            if(empty(name)){
                ZENG.msgbox.show('请输入任务名称', 5,2000);
                return false;
            }

            var model = $.trim($('input[name="model"]').val());
            if(empty(model)){
                ZENG.msgbox.show('请输入模型名', 5,2000);
                return false;
            }

            var method = $.trim($('input[name="method"]').val());
            if(empty(method)){
                ZENG.msgbox.show('请输入方法名', 5,2000);
                return false;
            }

            var cycle = $.trim($('input[name="cycle"]').val());
            if(empty(cycle)){
                ZENG.msgbox.show('请选择执行周期', 5,2000);
                return false;
            }

            return true;
        }

        function completeCronForm(data){
            if(data.status){
                ZENG.msgbox.show(data.info, 4,1000);
                setTimeout(function(){ location.href=URL+'/index'; },1000);
            } else {
                ZENG.msgbox.show(data.info, 5,2000);
            }
        }

        $('#detail_seo_form').ajaxForm({
            beforeSubmit:  checkForm,  // pre-submit callback
            success:       completeSeoData,  // post-submit callback
            dataType: 'json'
        });

        function completeSeoData(data){
            if (data.status==1){
                c.success(data.info,1000);
                location.href = URL + '/index';
            }else{
                c.error(data.info,2000);
                return false;
            }
        }

        //表单提交
        $('#detail_form').ajaxForm({
            beforeSubmit:  checkForm,  // pre-submit callback
            success:       complete,  // post-submit callback
            dataType: 'json'
        });

        function checkForm(){
            return true;
        }

        function complete(data){
            if (data.status==1){
                c.success(data.info,1000);
                $('textarea[name="content"]').val('');
                $('input[name="subject"]').val('');
                $('.type_4').find('input[name="txt_mobile"]').val('');
                $('.sys_msg select').val(0);
                window.location.reload();
            }else{
                c.error(data.info,2000);
                return false;
            }
        }


        //搜索展开、关闭
        $('.search,.cancel_search').click(function(){
            $('#search_form')[0].reset();
            $('#search_form').slideToggle('fast');
        });

        $('.checkall').checkAll('input[name="item[]"]');

        //日志多选项删除
        $('.dels').off().on('click',function(){
            var ids='';
            $('input[name="item[]"]:checked').each(function(){
                ids +=$(this).val()+',';
            });
            ids = ids.substring(0,ids.length-1);
            del(ids);
        });

        //单选删除
        $('.delLog').off().on('click',function(){
            var id = $(this).data('id');
            del(id);
        });

        //删除
        function del(id){
            if(empty(id)){
                c.error('请选择操作项！',2000);
                return false;
            }
            dialog({title:'温馨提示',height:100,icon:'warning',content:'是否确定删除？',ok:function(){
                $.post(URL+"/del",{id:id},function(data){
                    if(data.status == 1){
                        c.success(data.info,1000);
                        setTimeout(function(){ window.location.reload(); },1000);
                        $('input[type="checkbox"]').attr('checked',false);
                        return true;
                    }else{
                        c.error(data.info,2000);
                        return false;
                    }
                });
            },cancel:function(){},okVal:'确定',cancelVal:'取消'});
        }

        /////////////////////////////////群发短信//////////////////////////////
        //选择群发目的
        $('#type').selectbox({
            callback:function(v){
                var type = parseInt(v.attr('v'));
                if(type==1){
                    $('.type_1').removeClass('hidden');
                    $('.type_2,.type_3').removeClass('hidden').addClass('hidden');
                }else if(type == 3) {
                    $('.type_1,.type_2').removeClass('hidden').addClass('hidden');
                    $('.type_3').removeClass('hidden');
                } else if(type==4){
                    $('.type_1,.type_2,.type_3').removeClass('hidden').addClass('hidden');
                } else {
                    $('.type_2').removeClass('hidden');
                    $('.type_1,.type_3').removeClass('hidden').addClass('hidden');
                }
            }
        });


        //短信群发
        $('#detail_sms_batch_form').ajaxForm({
            beforeSubmit:checkSmsForm,
            success:complete,
            dataType:'json'
        });

        function checkSmsForm(){
            var type = $.trim($('#type').val());
            if(empty(type)){
                c.error('请选择群发类型',2000);
                return false;
            }

            if(type==1){
                //促销群发
                var promote = $.trim($('#promote').val());
                if(empty(promote)){
                    c.error('请选择促销期',2000);
                    return false;
                }
            }else if(type == 3){
                //手动输入
                var txt_mobile = $.trim($('input[name="txt_mobile"]').val());
                if(empty(txt_mobile)){
                    c.error('请输入发送的手机号！',2000);
                    $('input[name="txt_mobile"]').focus();
                    return false;
                }
            } else if(type==2) {
                //其他
                var mobile = $('input[name="mobile"]').val();
                if(empty(mobile)){
                    c.error('请选择导入文件',2000);
                    return false;
                }
            }

            var content = filterHtml($.trim($('textarea[name="content"]').val()));
            if(empty(content)){
                c.error('请输入短信内容',2000);
                return false;
            }
            if(getLength(content)>70){
                c.error('短信内容不能超过70个字',2000);
                return false;
            }

            return true;
        }

        //群发系统消息
        $('#notice_sel').selectbox({
            callback:function(v){
                var type = parseInt(v.attr('v'));
                if(type == 2){
                    $('.type_2').removeClass('hidden').addClass('show');
                }else{
                    $('.type_2').removeClass('show').addClass('hidden');
                }
            }
        });

        $('#sys_detail_form').ajaxForm({
            beforeSubmit:checkSysForm,
            success:complete,
            dataType:'json'
        });
        function checkSysForm(){
            var type = $.trim($('#notice_sel').val());
            if(empty(type)){
                c.error('请选择群发类型',2000);
                return false;
            }

            if(type == 2){
                var mobile = $('input[name="mobile"]').val();
                if(empty(mobile)){
                    c.error('请选择导入文件',2000);
                    return false;
                }
            }

            var content = $.trim($('textarea[name="content"]').val());
            if(empty(content)){
                c.error('请输入系统消息内容',2000);
                return false;
            }
            return true;
        }

        $('.sel_user').click(function(){
            var url = URL+'/contact';
            var uids = $('#sendinfo').find('input[name="uids"]').val();
            dialog({title:'选择联系人',width:620,url:url+"?uids="+uids,end:function(){
                var body=this.c('body');
                var btn=body.find('.btn-primary');
                body.find('.checkall').checkAll(body.find('input[name="item[]"]'));
                body.delegate('.dsearch .btn-primary','click',function(){
                $.get(url+"?kw="+body.find('input[name="kw"]').val(),function(data){
                    body.html(data);
                    c.hide();
                    body.find('.checkall').checkAll(body.find('input[name="item[]"]'));
                },'html');
                });
                //ajax分页
                body.delegate('.page a','click',function(){
                    c.wait('加载中');
                    var url = $(this).attr('href');
                    $.get(url,'',function(data){
                        body.html(data);
                        c.hide();
                        body.find('.checkall').checkAll(body.find('input[name="item[]"]'));
                    },'html');
                    return false;
                });
            },ok:function(){
                var body=this.c('body');
                var temp=Array();
                var selected='';
                var ids=$('#sendinfo').find('input[name="uids"]').val();
                if(ids){
                    ids=temp=ids.split(',');
                }else{
                    ids=temp=[];
                }

                body.find('input[name="item[]"]:checked').each(function(){
                    var id=$(this).val();
                    if($.inArray(id,ids)<0){
                        temp.push(id);
                        var li = $(this).closest('tr');
                        var name=li.data('name');
                        var item=[id,name];
                        selected+='<a href="javascript:;" data-uid="'+id+'" code="'+item+'">'+name+'</a>';
                    }
                });
                $('#sendinfo').find('input[name="uids"]').val(temp.join(','));
                $('#sendinfo').find('.result').append(selected);

            },cancel:function(){}});
        });

        //选择删除
        $('#sendinfo .result').delegate('a','click',function(){
            var t = $(this).parent();
            var uids = $('#sendinfo').find('input[name="uids"]');
            $(this).fadeOut(function(){
                $(this).remove();

                var tmp=[];
                t.find('a').each(function(){
                    tmp.push($(this).data('uid'));
                });
                uids.val(tmp.join(','));
            });
        });

        //重新统计
        $('.recount').off().on('click',function(){
            $.post(URL+'/recount','',function(data){
                location.reload();
            },'json')
        });

        //删除意见反馈
        $('table .del').off().on('click',function(){
            var id = $(this).data('id');
            if(empty(id)){
                c.error('请选择操作项！',2000);
                return false;
            }

            dialog({title:'温馨提示',height:100,icon:'warning',content:'是否确定删除？',ok:function(){
                $.get(URL+'/del?id='+id,'',function(data){
                    if(data.status==1){
                        c.success(data.info,1000);
                        setTimeout(function(){
                            location.reload();
                        },1500);
                    } else {
                        c.error(data.info,2000);
                        return false;
                    }
                },'json');
            },cancel:function(){},okVal:'确定',cancelVal:'取消'});
        });

    });
});